package blog.caidabao.controller;

import blog.caidabao.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

@Controller
@RequestMapping("visitor")
public class VisitorController {
    @Autowired
    private RedisService redisService;

    @PostMapping("update")
    public void updateRecentVisitors(@RequestParam("LastVisitor") String LastVisitor){
        this.redisService.UpdateRecentVisiotrs(LastVisitor);
    }

    @GetMapping
    public ResponseEntity<List<String>> getRecentVisitors(){
        Set<ZSetOperations.TypedTuple<String>> recent_visitors = this.redisService.revrangeWithScore2("recent_visitors", 0, -1);
        Iterator<ZSetOperations.TypedTuple<String>> visitorsIterator=recent_visitors.iterator();
        List<String> visitorsList=new ArrayList<>();
        while(visitorsIterator.hasNext()){
             visitorsList.add(visitorsIterator.next().getValue());
        }
        return ResponseEntity.ok(visitorsList);
    }
}
